package com.ybbase.framework.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ybbase.framework.base.service.TreeService;
import com.ybbase.framework.common.util.StringsUtil;
import com.ybbase.framework.mapper.system.*;
import com.ybbase.framework.model.po.system.*;
import com.ybbase.framework.model.vo.MenuVO;
import com.ybbase.framework.model.vo.PermissionTreeVO;
import com.ybbase.framework.service.system.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 系统菜单 服务实现类
 * </p>
 *
 * @author cg
 * @since 2019-11-26
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    RolePermissionMapper rolePermissionMapper;
    @Autowired
    TreeService treeService;
    @Autowired
    UserPermissionMapper userPermissionMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    DictMapper dictMapper;

    /**
     * 保存权限
     *
     * @param permission 权限信息
     * @author cg
     * @date 2019-11-29 17:37
     * @since cloud2.0
     */
    @Override
    public void savePermission(Permission permission) {
        permissionMapper.insert(permission);
    }

    /**
     * 根据角色编码组合获取权限列表
     *
     * @param roleIds 角色编码
     * @return List<Permission>
     * @author cg
     * @date 2019-11-26 17:41
     * @since cloud2.0
     */
    @Override
    public List<Permission> getPermissionInRoleIds(String roleIds) {
        return permissionMapper.getPermissionByIds(roleIds.split(","));
    }

    /**
     * 根据角色编码组合获取权限列表
     *
     * @param roleIds 角色编码
     * @return List<Permission>
     * @author cg
     * @date 2019-11-26 17:41
     * @since cloud2.0
     */
    @Override
    public List<Permission> getPermissionButtonInRoleIds(String roleIds) {
        return permissionMapper.getPermissionButtonByIds(roleIds.split(","));
    }

    /**
     * 根据用户编码获取权限树
     *
     * @param userId 用户编码
     * @return List<PermissionTreeVO>
     * @author cg
     * @date 2019-12-01 20:52
     * @since cloud2.0
     */
    @Override
    public List<MenuVO> getPermissionTreeVOByUserId(Integer userId) {
        List<Permission> sourceList = new ArrayList<>();
        //QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        //queryWrapper.lambda().eq(UserRole::getUserId, userId);
        //List<UserRole> userRoles = userRoleMapper.selectList(queryWrapper);
        //String roleIds = "";
        //if (userRoles!=null&&!userRoles.isEmpty()){
        //    for(UserRole userRole:userRoles){
        //        roleIds = roleIds + userRole.getRoleId() +",";
        //    }
        //}
        //sourceList = permissionMapper.getPermissionByIds(roleIds.split(","));
        sourceList = permissionMapper.getPermissionByUserId(userId);
        return this.findSortPermission(sourceList);
    }
    /**
     * 根据角色编码
     *
     * @param roleId@return
     * @author cg
     * @date 2020-01-12 13:28
     * @since cloud2.0
     */
    @Override
    public List<PermissionTreeVO> getPermissionTreeVOByRoleId(String roleId) {
        List<Permission> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(roleId)){
            list = getPermissionByRoleId(Integer.parseInt(roleId));
        }
        List<Permission> sourceList = permissionMapper.selectList(new QueryWrapper<>());
        return this.findSortPermissionTreeVO(sourceList,list);
    }

    /**
     * 根据角色编码
     *
     * @param roleId@return
     * @author cg
     * @date 2020-01-12 13:28
     * @since cloud2.0
     */
    @Override
    public List<PermissionTreeVO> getPermissionTreeVOByRoleIdCg(Integer userId,String roleId) {
        List<Permission> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(roleId)){
            String[] roleIds = roleId.split(",");
            list = getPermissionByRoleIds(userId,roleIds);
        }
        //List<Permission> sourceList = permissionMapper.selectList(new QueryWrapper<>());
        return this.findSortPermissionTreeVO(list,list);
    }

    /**
     * 获取所有权限
     *
     * @return List<Permission>
     * @author cg
     * @date 2019-11-29 17:37
     * @since cloud2.0
     */
    @Override
    public List<Permission> getAllPermission(QueryWrapper<Permission> queryPermission) {
        return permissionMapper.selectList(queryPermission);
    }

    /**
     * 根据角色获取权限列表（带排序）
     *
     * @param roleId 角色编码
     * @return List<Permission>
     * @author cg
     * @date 2019-11-29 17:29
     * @since cloud2.0
     */
    @Override
    public List<Permission> getPermissionByRoleId(Integer roleId) {
        return permissionMapper.getPermissionByRoleId(roleId);
    }

    public List<Permission> getPermissionByRoleIds(Integer userId,String[] roleIds){
        List<Permission> list = new ArrayList<>();
        Integer ids = 0;
        if (roleIds!=null&&roleIds.length>0){
            for(String roleId:roleIds){
                Role role = roleMapper.selectById(Integer.parseInt(roleId));
                if(ids<role.getDataScope()){
                    ids = role.getDataScope();
                }
            }
        }
        list = permissionMapper.getPermissionByIdsCg(roleIds);
        if (list!=null&&!list.isEmpty()){
            for(Permission permission:list){
                QueryWrapper<UserPermission> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(UserPermission::getUserId, userId);
                queryWrapper.lambda().eq(UserPermission::getPerId, permission.getId());
                UserPermission userPermission = userPermissionMapper.selectOne(queryWrapper);
                if(userPermission!=null){
                    QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
                    dictQueryWrapper.lambda().eq(Dict::getDictkey, userPermission.getDataScope());
                    dictQueryWrapper.lambda().eq(Dict::getType, "data_permission");
                    permission.setRouterName(permission.getRouterName()+"("+
                            dictMapper.selectOne(dictQueryWrapper).getDictvalue()+")");
                    permission.setDataScope(userPermission.getDataScope()+"");
                }else {
                    QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
                    dictQueryWrapper.lambda().eq(Dict::getDictkey, ids);
                    dictQueryWrapper.lambda().eq(Dict::getType, "data_permission");
                    permission.setRouterName(permission.getRouterName()+"("+
                            dictMapper.selectOne(dictQueryWrapper).getDictvalue()+")");
                    permission.setDataScope(userPermission.getDataScope()+"");
                }
            }
        }
        return list;
    }

    /**
     * 查询排序的菜单权限 用户和角色编码只能存在一个
     *
     * @param list   权限列表
     * @param roleId 角色编码
     * @param userId 用户编码
     * @return List<PermissionTreeVO>
     * @author cg
     * @date 2019-12-01 09:32
     * @since cloud2.0
     */
    @Override
    public List<MenuVO> findSortPermission(List<Permission> list) {
        List<MenuVO> firstList = new ArrayList<>();
        List<MenuVO> sourceList = new ArrayList<>();
        for (Permission tp : list) {
            //RolePermission rolePermission = new RolePermission();
            //UserPermission userPermission = new UserPermission();
            //if (StringUtils.isNotEmpty(roleId)) {
            //    QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
            //    queryWrapper.lambda().eq(RolePermission::getRoleId, roleId);
            //    queryWrapper.lambda().eq(RolePermission::getPerId, tp.getId());
            //    rolePermission = rolePermissionMapper.selectOne(queryWrapper);
            //}
            //if (StringUtils.isNotEmpty(userId)) {
            //    QueryWrapper<UserPermission> queryWrapper = new QueryWrapper<>();
            //    queryWrapper.lambda().eq(UserPermission::getUserId, userId);
            //    queryWrapper.lambda().eq(UserPermission::getPerId, tp.getId());
            //    userPermission = userPermissionMapper.selectOne(queryWrapper);
            //}
            //MenuVO menuVO = treeService.assembleMenuVO(tp, StringUtils.isNotEmpty(userPermission.getButtonPer()) ? userPermission.getButtonPer() : rolePermission.getButtonPer());
            MenuVO menuVO = treeService.assembleMenuVO(tp, null);
            if (tp.getParentId() == 0) {
                firstList.add(menuVO);
            }
            sourceList.add(menuVO);
        }
        treeService.sortPermissionTree(firstList, sourceList);
        return firstList;
    }

    /**
     * 根据角色类表查询相关数据
     * @param
     * @return
     * @author cg
     * @date 2020-01-12 15:06
     * @since cloud2.0
    */
    public List<PermissionTreeVO> findSortPermissionTreeVO(List<Permission> list,List<Permission> rolePermissionList){
        List<PermissionTreeVO> firstList = new ArrayList<>();
        List<PermissionTreeVO> sourceList = new ArrayList<>();
        for (Permission tp : list) {
            boolean check =false;
            if(rolePermissionList!=null&&!rolePermissionList.isEmpty()){
                for(Permission rp:rolePermissionList){
                    if(rp.getId().equals(tp.getId())){
                        check = true;
                        tp.setRouterName(rp.getRouterName());
                        tp.setDataScope(rp.getDataScope());
                        break;
                    }
                }
            }
            PermissionTreeVO permissionTreeVO = treeService.assemblePermissionTreeVO(tp,check);
            if (tp.getParentId() == 0) {
                firstList.add(permissionTreeVO);
            }
            sourceList.add(permissionTreeVO);
        }
        treeService.sortPermissionTreeVO(firstList, sourceList);
        return firstList;
    }

    /**
     * 查询角色权限信息
     *
     * @param queryWrapper 条件
     * @return List<PermissionTreeVO>
     * @author cg
     * @date 2019-12-01 09:32
     * @since cloud2.0
     */
    @Override
    public List<RolePermission> getRolePermissionListByPerId(QueryWrapper<RolePermission> queryWrapper) {
        return rolePermissionMapper.selectList(queryWrapper);
    }

    /**
     * @param
     * @return
     * @author jzw
     * @date 2019/12/6 13:48
     * @since cloud2.0
     */
    @Override
    public Permission getPermissionPathByPerId(Integer parenId) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Permission::getParentId, parenId);
        return permissionMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Permission> getPerTree() {
        return permissionMapper.getPerTree();
    }

    @Override
    public IPage<Permission> findByParentId(IPage<Permission> page, QueryWrapper<Permission> queryWrapper, Integer parentId) {
        return permissionMapper.findByParentId(page, queryWrapper, parentId);
    }

    @Override
    public void savePermissionMenu(Permission permission) {
        if (permission != null) {
            Permission permissionData = new Permission();
            String path = "";
            if (permission.getParentId() != null && permission.getParentId() != 0) {
                permissionData = permissionMapper.selectById(permission.getParentId());
                permission.setParentName(permissionData.getRouterName());
                path = permissionData.getPath();
            } else {
                permission.setParentId(0);
            }
            if (permission.getId() != null && permission.getId() != 0) {
                permission.setPath(path + permission.getId() + "|");
                permissionMapper.updateById(permission);
            } else {
                permissionMapper.insert(permission);
                permission.setPath(path + permission.getId() + "|");
                permissionMapper.updateById(permission);
            }
        }
    }

    /**
     * 保存用户权限数据权限
     * @param
     * @return
     * @author cg
     * @date 2020-03-26 10:37
     * @since cloud2.0
    */
    @Override
    public void saveUserPermission(Integer perId,Integer userId,Integer dataScope){
        UpdateWrapper<UserPermission> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(UserPermission::getUserId, userId);
        updateWrapper.lambda().eq(UserPermission::getPerId, perId);
        UserPermission userPermission = new UserPermission();
        userPermission.setDataScope(dataScope);
        userPermissionMapper.update(userPermission, updateWrapper);
    }

}
